<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商家ID" prop="merchantId">
        <el-input
          v-model="queryParams.merchantId"
          placeholder="请输入商家ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资讯类型" prop="newsType">
        <el-select
          v-model="queryParams.newsType"
          placeholder="请选择资讯类型"
          clearable
        >
          <el-option
            v-for="dict in news_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布时间" prop="publishTime">
        <el-date-picker
          clearable
          v-model="queryParams.publishTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择发布时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="expireTime">
        <el-date-picker
          clearable
          v-model="queryParams.expireTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间"
        >
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="是否置顶" prop="isTop">
        <el-select v-model="queryParams.isTop" placeholder="请选择是否置顶" clearable>
          <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="发布状态" prop="isPublished">
        <el-select v-model="queryParams.isPublished" placeholder="请选择发布状态" clearable>
          <el-option v-for="dict in published_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="是否启用" prop="isEnabled">
        <el-select
          v-model="queryParams.isEnabled"
          placeholder="请选择是否启用"
          clearable
        >
          <el-option
            v-for="dict in sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in wdm_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi:newsInfo:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi:newsInfo:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi:newsInfo:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ruoyi:newsInfo:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="newsInfoList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        min-width="60"
        align="center"
        prop="newsId"
      />
      <el-table-column label="商家ID" align="center" prop="merchantId" />

      <el-table-column
        label="标题"
        align="center"
        prop="title"
        min-width="200"
        show-overflow-tooltip
      />

      <!-- 表格内容列超出一行隐藏显示, 其实内容没有必要展示出来啊 -->
      <!-- <el-table-column label="内容" align="center" prop="content" /> -->

      <!-- <el-table-column label="内容" align="center" prop="contentText" min-width="200" show-overflow-tooltip /> -->

      <!-- <el-table-column label="内容" align="center" min-width="200" show-overflow-tooltip>
        <template #default="scope">
          {{ stripHtml(scope.row.content) }}
        </template>
</el-table-column> -->

      <el-table-column
        label="宣传图"
        align="center"
        prop="coverImage"
        width="100"
      >
        <template #default="scope">
          <image-preview :src="scope.row.coverImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="资讯类型" align="center" prop="newsType">
        <template #default="scope">
          <dict-tag :options="news_type" :value="scope.row.newsType" />
        </template>
      </el-table-column>
      <el-table-column
        label="发布时间"
        align="center"
        prop="publishTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.publishTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        align="center"
        prop="expireTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.expireTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="置顶" align="center" prop="isTop">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isTop" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="发布状态" align="center" prop="isPublished">
        <template #default="scope">
          <dict-tag :options="published_type" :value="scope.row.isPublished" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="是否启用" align="center" prop="isEnabled">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isEnabled" />
        </template>
      </el-table-column> -->
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />

      <el-table-column
        label="操作"
        align="center"
        min-width="150"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:newsInfo:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:newsInfo:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改动态资讯对话框 -->
    <el-dialog
      :key="dialogKey"
      :title="title"
      v-model="open"
      width="50%"
      append-to-body
    >
      <el-form
        ref="newsInfoRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="商家ID" prop="merchantId">
          <el-input v-model="form.merchantId" placeholder="请输入商家ID" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>

        
        <!-- <el-form-item label="宣传图" prop="coverImage">
          <image-upload v-model="form.coverImage" />
        </el-form-item> -->

        <el-form-item label="宣传图" prop="coverImage">
          <image-upload
            v-model="form.coverImage"
            :auto-upload="false"
            :show-tip="true"
          />
        </el-form-item>

        <el-form-item label="资讯类型" prop="newsType">
          <el-select v-model="form.newsType" placeholder="请选择资讯类型">
            <el-option
              v-for="dict in news_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            clearable
            v-model="form.publishTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择发布时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="expireTime">
          <el-date-picker
            clearable
            v-model="form.expireTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="置顶" prop="isTop">
          <el-select v-model="form.isTop" placeholder="请选择是否置顶">
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态" prop="isPublished">
          <el-select v-model="form.isPublished" placeholder="请选择发布状态">
            <el-option
              v-for="dict in published_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnabled">
          <el-select v-model="form.isEnabled" placeholder="请选择是否启用">
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in wdm_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除" prop="delFlag">
          <el-radio-group v-model="form.delFlag">
            <el-radio
              v-for="dict in del_flag"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="NewsInfo">
import { ref, nextTick } from "vue";
import {
  listNewsInfo,
  getNewsInfo,
  delNewsInfo,
  addNewsInfo,
  updateNewsInfo,
} from "@/api/ruoyi/newsInfo";

const { proxy } = getCurrentInstance();
const { published_type, wdm_status, sys_yes_no, news_type, del_flag } =
  proxy.useDict(
    "published_type",
    "wdm_status",
    "sys_yes_no",
    "news_type",
    "del_flag"
  );

const newsInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const dialogKey = ref(0);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merchantId: null,
    title: null,
    content: null,
    coverImage: null,
    newsType: null,
    publishTime: null,
    expireTime: null,
    isTop: null,
    isPublished: null,
    isEnabled: null,
    status: null,
  },
  rules: {
    merchantId: [
      { required: true, message: "商家ID不能为空", trigger: "blur" },
    ],
    title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询动态资讯列表 */
function getList() {
  loading.value = true;
  listNewsInfo(queryParams.value).then((response) => {
    // newsInfoList.value = response.rows
    // 过滤已删除数据（假设 delFlag 字段标识删除状态）
    newsInfoList.value = response.rows.filter((item) => item.delFlag !== "2");
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询动态资讯列表 */
// function getList() {
//   loading.value = true
//   listNewsInfo(queryParams.value).then(response => {
//     // 预处理内容字段
//     const processedData = response.rows.filter(
//       (item) => item.delFlag !== "2"
//     ).map(item => ({
//       ...item,
//       contentText: stripHtml(item.content, 50)
//     }));

//     newsInfoList.value = processedData;
//     total.value = response.total
//     loading.value = false
//   })
// }

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    newsId: null,
    merchantId: null,
    title: null,
    // content: null,
    content: "",
    coverImage: null,
    newsType: null,
    publishTime: null,
    expireTime: null,
    isTop: null,
    isPublished: null,
    isEnabled: null,
    status: null,
    delFlag: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  proxy.resetForm("newsInfoRef");

  // 使用nextTick确保DOM更新后操作编辑器
  nextTick(() => {
    // 方法1：直接操作编辑器实例（如果可用）
    const editor = document.querySelector(".editor-class .ql-editor");
    if (editor) {
      editor.innerHTML = "";
    }

    // 方法2：如果使用的是特定编辑器库，调用其reset方法
    // 例如：如果使用Quill编辑器
    // if (window.quillInstances && window.quillInstances['newsContentEditor']) {
    //   window.quillInstances['newsContentEditor'].setText('')
    // }
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.newsId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  dialogKey.value++; // 改变key强制重新渲染对话框
  open.value = true;
  title.value = "添加动态资讯";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _newsId = row.newsId || ids.value;
  getNewsInfo(_newsId).then((response) => {
    form.value = response.data;
    dialogKey.value++; // 改变key强制重新渲染对话框
    open.value = true;
    title.value = "修改动态资讯";
  });
}

// 新增图片压缩工具函数（与轮播图管理保持一致）
const smartCompressImage = async (base64, options = {}) => {
  const {
    maxWidth = 1080,
    maxHeight = 1920,
    quality = 0.6,
    format = "webp",
  } = options;
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = base64;
    img.onload = () => {
      const canvas = document.createElement("canvas");
      let { width, height } = img;

      // 保持比例缩放
      if (width > maxWidth) {
        height = Math.round((height * maxWidth) / width);
        width = maxWidth;
      }
      if (height > maxHeight) {
        width = Math.round((width * maxHeight) / height);
        height = maxHeight;
      }

      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, width, height);

      try {
        const compressed = canvas.toDataURL(`image/${format}`, quality);
        console.log(
          `[图片压缩] 原尺寸: ${img.width}x${
            img.height
          }, 新尺寸: ${width}x${height}, 压缩率: ${Math.round(
            (compressed.length / base64.length) * 100
          )}%`
        );
        resolve(compressed);
      } catch (e) {
        reject(new Error("Canvas压缩失败: " + e.message));
      }
    };
    img.onerror = reject;
  });
};

// 新增图片上传处理函数
const uploadProcessedImage = async (base64Data) => {
  const blob = await (await fetch(base64Data)).blob();
  const formData = new FormData();
  formData.append("file", blob, `news_cover_${Date.now()}.webp`);

  try {
    const response = await proxy.$http.post("/common/upload", formData, {
      headers: { "Content-Type": "multipart/form-data" },
    });

    // 修复1: 正确解析若依框架的响应结构 (data.fileName)
    const fileName = response.data?.fileName;
    if (!fileName) {
      throw new Error("服务器返回格式异常: " + JSON.stringify(response));
    }

    // 修复2: 统一路径格式处理
    return fileName.startsWith("/profile") ? fileName : "/profile" + fileName;
  } catch (error) {
    // 修复3: 详细错误日志
    console.error("[图片上传] 失败详情:", {
      status: error.response?.status,
      data: error.response?.data,
      message: error.message,
    });
    throw new Error(
      `图片上传失败: ${error.response?.data?.msg || error.message}`
    );
  }
};

/** 提交按钮 */
function submitForm() {
  proxy.$refs["newsInfoRef"].validate((valid) => {
    if (valid) {
      if (form.value.newsId != null) {
        updateNewsInfo(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addNewsInfo(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _newsIds = row.newsId || ids.value;
  proxy.$modal
    .confirm('是否确认删除动态资讯编号为"' + _newsIds + '"的数据项？')
    .then(function () {
      return delNewsInfo(_newsIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/newsInfo/export",
    {
      ...queryParams.value,
    },
    `newsInfo_${new Date().getTime()}.xlsx`
  );
}

/**
 * 去除HTML标签，返回纯文本
 * @param {string} html - 包含HTML的内容
 * @returns {string} 纯文本内容
 */
// function stripHtml(html) {
//   if (!html) return '';
//   // 创建临时div用于解析HTML
//   const tempDiv = document.createElement('div');
//   tempDiv.innerHTML = html;
//   // 返回纯文本并去除多余空格
//   return tempDiv.textContent?.replace(/\s+/g, ' ').trim() || '';
// }

function stripHtml(html, maxLength = 50) {
  if (!html) return "";
  const tempDiv = document.createElement("div");
  tempDiv.innerHTML = html;
  const text = tempDiv.textContent?.replace(/\s+/g, " ").trim() || "";

  // 限制显示字符数
  if (text.length > maxLength) {
    return text.substring(0, maxLength) + "...";
  }
  return text;
}

getList();
</script>

<style lang="scss" scoped>
/* 确保表格内容单元格正确显示省略号 */
.el-table__body td {
  .cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
